import React, { useRef, useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { View, Image, Text, ScrollView } from '@tarojs/components';
import { sourceUrl } from '@/config';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import StandModal from '@/components/StandModal';
import Icon from '@/components/Icon';
import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import pLocation from '@/orderSubPack/images/order/location.png';
import pQuxiao from '@/orderSubPack/images/order/quxiao.png';
import pWancheng from '@/orderSubPack/images/order/wancheng.png';
import pWait from '@/orderSubPack/images/order/wait.png';
import pCar from '@/orderSubPack/images/order/sendCar.png';
import pCopy from '@/images/common/copy.svg';
import pCancle from '@/orderSubPack/images/order/quxiao1.png';
import pCallShop from '@/orderSubPack/images/order/callshangjia.png';
import pCallDriver from '@/orderSubPack/images/order/callqishou.png';
import pAfterSale from '@/orderSubPack/images/order/afterSale.png';
import pAfterSaleDetail from '@/orderSubPack/images/order/afterSaleDetail.png';

import OrderCancleReason from '../orderCancleReason/index';

import './index.scss';
import { shopPay } from '@/utils/pay';

const initConfig = () => {
  return { titleName: '', titleIcon: null, statusDom: null, btns: [] };
};
const OrderDetail = ({ dispatch }) => {
  const [orderDetail, setOrderDetail] = useState({});
  const urlParms = useRef({});
  const renderInfo = useRef(initConfig());
  //start--售后确认弹框
  const [isOpenedGot, setIsOpenedGot] = useState(false);
  const applyParamsRef = useRef({});

  const handleClose = () => {
    isOpenedGot && setIsOpenedGot(false);
  };

  const handleGot = () => {
    setIsOpenedGot(false);
    confirmTakeGoods();
    goApplyAfterSale();
  };
  //end--售后确认弹框

  //start--取消订单、选择取消原因
  const [isOpened, setIsOpened] = useState(false);
  const opOrderId = useRef();

  const setOpOrderId = (orderId) => {
    opOrderId.current = orderId;
  };

  const cancleReasonClosed = () => {
    setIsOpened(false);
  };

  useDidShow(() => {
    init();
  });

  const handleSelected = (reasonStatus) => {
    setIsOpened(false);
    dispatch({
      type: 'order/orderCancleModel',
      payload: {
        orderId: opOrderId.current,
        orderCancelReasonStatus: reasonStatus,
      },
    }).then(() => {
      getOrderDetail(true);
    });
  };

  const handleCancleOrder = ({ orderId }) => {
    setOpOrderId(orderId);
    setIsOpened(true);
  };
  //end--取消订单、选择取消原因

  //start--发票信息
  const handleVoinceInfo = ({ einvoiceId }) => {
    Taro.navigateTo({
      url: '/orderSubPack/invoiceManagement/invoiceDetails/index?id=' + einvoiceId,
    });
  };
  //end--发票信息

  //start--确认收货
  const confirmTakeGoods = (theOrderId = null) => {
    let paramsConfirm = {};
    if (theOrderId) {
      paramsConfirm.orderId = theOrderId;
    } else {
      const { orderId, detailOrderId = null } = applyParamsRef.current;
      paramsConfirm.orderId = orderId;
      if (detailOrderId) {
        paramsConfirm.detailOrderId = detailOrderId;
      }
    }

    dispatch({
      type: 'order/confirmGetItemModel',
      payload: { ...paramsConfirm },
    }).then(() => getOrderDetail(true));
  };

  const handleSureGot = ({ orderId }) => {
    Taro.showModal({
      title: '操作提示',
      content: '请确保您已经收到货物，避免造成不必要的损失',
      cancelColor: '#000000',
      confirmColor: '#0091F2',
      success: function (res) {
        if (res.confirm) {
          confirmTakeGoods(orderId);
        } else if (res.cancel) {
        }
      },
    });
  };
  //end--确认收货

  const shopPayFail = (txt) => {
    return Taro.showModal({
      title: '买单提示',
      content: txt,
      confirmColor: '#576B95',
    });
  };

  const shopPaySuccess = ({ orderId }) => {
    // 刷新订单列表
    dispatch({
      type: 'order/setRefreshOrderId',
      payload: orderId,
    });

    let url = '/mainSubPack/shopPayResult/index?orderId=' + orderId;
    Taro.redirectTo({
      url,
    });
  };

  //start--立即支付
  const handlePayNow = ({ detail }) => {
    if (detail.type === 5) {
      shopPay(dispatch, {
        ...detail,
        orderId: detail.id,
        orgId: detail.storeId,
        orgName: detail.storeName,
      })
        .then(shopPaySuccess)
        .catch((e) => {
          const { txt } = e?.extra ?? {};
          shopPayFail(txt);
        });

      return;
    }

    Taro.redirectTo({url:`/pages/fineEngine/payment?id=${detail.id}`})
  };
  //end--立即支付

  //start--联系商家/骑手
  const handleConcat = ({ mobile, id }) => {
    if (mobile && mobile.length > 0) {
      Taro.makePhoneCall({
        phoneNumber: mobile,
      });
    }
    if (id) {
      Taro.navigateTo({ url: `/orderSubPack/submitComment/index?id=${id}&appId=thjs_takeout_org` });
    }
  };
  //end--联系商家/骑手

  //申请售后按钮
  const handleApplyAfterSale = (applyParams) => {
    applyParamsRef.current = applyParams;
    if (orderDetail.status == 6) {
      setIsOpenedGot(true);
    } else {
      goApplyAfterSale();
    }
  };

  const handleApplyAfterSaleForTakeout = (applyParams) => {
    applyParamsRef.current = applyParams;
    goApplyAfterSale();
  };

  const goApplyAfterSale = () => {
    const { kind, orderId, orderItemId, mobile, isTakeOut = false } = applyParamsRef.current;
    if (kind == 1) {
      //退款
      Taro.navigateTo({
        url: `/orderSubPack/afterSale/applyRefund/index?kind=${kind}&orderId=${orderId}&mobile=${mobile}&isTakeOut=${isTakeOut}`,
      });
    } else {
      //退货/换货
      Taro.navigateTo({
        url: `/orderSubPack/afterSale/applyType/index?kind=${kind}&orderId=${orderId}&orderItemId=${orderItemId}`,
      });
    }
  };

  //跳转到售后列表页
  const handleGoAfterSaleDetail = ({id}) => {
    Taro.navigateTo({ url: `/orderSubPack/afterSale/detail/index?id=${id}` });
  };

  //退货换货时展示商品信息
  const saveProductInfo = (productInfo) => {
    dispatch({
      type: 'order/setProductInfoForAfterSale',
      payload: productInfo,
    });
  };

  //刷新订单列表
  const refreshOrderList = (orderId) => {
    dispatch({
      type: 'order/setRefreshOrderId',
      payload: orderId,
    });
  };

  const saveOrderDetail = (info) => {
    dispatch({
      type: 'order/saveOrderDetail',
      payload: { ...info },
    });
  };

  const getOrderDetail = (isNeedRefreshOrderList = false) => {
    renderInfo.current = initConfig();
    dispatch({
      type: 'order/orderDetailModel',
      payload: { orderId: urlParms.current.orderId },
    }).then((data) => {
      let deliveryTimeObj = data.deliveryTime ? JSON.parse(data.deliveryTime) : { startTime: '' };
      data.deliveryStartTime = deliveryTimeObj.startTime;
      data.deliveryEndTime = deliveryTimeObj.endTime;
      createStatusInfo(data);
      setOrderDetail(data);
      saveOrderDetail(data);
      if (isNeedRefreshOrderList) {
        refreshOrderList(data.id);
      }
    });
  };

  const init = () => {
    urlParms.current = getCurrentInstance().router.params;
    let isNeedRefreshOrderList = false;
    if (urlParms.current.isNeedRefreshOrderList) {
      isNeedRefreshOrderList = true;
    }
    if (Taro.$isH5) {
      if (urlParms.current.from == 'wxPay') {
        let url = window.location.origin + '/pages/mainPages/homePage/homePage';
        window.history.pushState({ page: 1 }, '', url);
        window.addEventListener(
          'popstate',
          () => {
            window.location.href = url;
          },
          false,
        );
      }
    }
    getOrderDetail(isNeedRefreshOrderList);
  };

  // useEffect(() => {
  //   init();
  // }, []);

  const createStatusInfo = (detail) => {
    //1待支付 2已关闭 3已取消 4已完成 5待发货 6配送中
    switch (detail.status) {
      case 1:
        renderInfo.current.titleName = '等待付款';
        renderInfo.current.titleIcon = pWait;
        renderInfo.current.statusDom = (
          <OrderWaitPayInfo orderDetail={detail} dispatch={dispatch} refresh={getOrderDetail} />
        );
        renderInfo.current.btns.push({
          name: '取消订单',
          func: handleCancleOrder,
          params: { orderId: detail.id },
          imgSrc: pCancle,
        });
        renderInfo.current.btns.push({
          name: '立即支付',
          isOutStanding: true,
          func: handlePayNow,
          params: { detail },
          isAll: true,
          imgSrc: 'a-tubiaoai_huaban2fuben5',
          isIcon: true,
        });
        if (
          detail.distributeType == 2 ||
          detail.distributeType == 3 ||
          detail.distributeType == 4
        ) {
          renderInfo.current.statusTipDom = (
            <OrderWaitPayInfoTakeOut orderDetail={detail} dispatch={dispatch} refresh={getOrderDetail} />
          );
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
        }
        break;
      case 2:
        renderInfo.current.titleName = '已关闭';
        break;
      case 3:
        renderInfo.current.titleName = '已取消';
        renderInfo.current.titleIcon = pQuxiao;
        renderInfo.current.statusDom = <OrderCancleInfo orderDetail={detail} />;
        // detail.einvoiceId &&
        //   detail.distributeType == 1 &&
        //   renderInfo.current.btns.push({
        //     name: '发票信息',
        //     func: handleVoinceInfo,
        //     params: { einvoiceId: detail.einvoiceId },
        //   });
        if (
          detail.distributeType == 2 ||
          detail.distributeType == 3 ||
          detail.distributeType == 4
        ) {
          renderInfo.current.statusTipDom = (
            <View className="statusTip">
              <Text className="text">{'该订单已取消：' + detail.cancelReason}</Text>
            </View>
          );
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
        }
        break;
      case 4:
        renderInfo.current.titleName = '已完成';
        renderInfo.current.titleIcon = pWancheng;
        renderInfo.current.statusDom = <OrderCompleteInfo orderDetail={detail} />;
        detail.einvoiceId &&
          detail.distributeType == 1 &&
          renderInfo.current.btns.push({
            name: '发票信息',
            func: handleVoinceInfo,
            params: { einvoiceId: detail.einvoiceId },
          });
        if (
          detail.distributeType == 2 ||
          detail.distributeType == 3 ||
          detail.distributeType == 4
        ) {
          renderInfo.current.statusTipDom = (
            <View className="statusTip">
              <Text className="text">感谢您的信任和支持，期待再次光临。</Text>
            </View>
          );
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
          detail.distributeType == 2 &&
            renderInfo.current.btns.push({
              name: '致电骑手',
              func: handleConcat,
              params: { mobile: detail.dmMobile },
              imgSrc: pCallDriver,
              size4: true,
            });
        }
        break;
      case 5:
        renderInfo.current.titleName = '待发货';
        renderInfo.current.statusDom = <OrderWaitSendInfo />;
        detail.einvoiceId &&
          detail.distributeType == 1 &&
          renderInfo.current.btns.push({
            name: '发票信息',
            func: handleVoinceInfo,
            params: { einvoiceId: detail.einvoiceId },
          });

        if (detail?.items[0]?.isApplyAdjustment == 1) {
          renderInfo.current.btns.push({
            name: '售后详情',
            func: handleGoAfterSaleDetail,
            params: {id:detail?.items[0]?.orderAdjustmentId},
            imgSrc: pAfterSaleDetail,
          });
        }

        if (detail.distributeType == 2 || detail.distributeType == 3) {
          renderInfo.current.titleName = '待接单';
          renderInfo.current.statusTipDom = (
            <View className="statusTip">
              <View className="text">商家暂未接单，请耐心等待</View>
            </View>
          );
          if (detail?.items[0]?.isShowAdjustment == 1) {
            renderInfo.current.btns.push({
              name: '申请退款',
              func: handleApplyAfterSaleForTakeout,
              params: {
                kind: 1,
                orderId: detail.id,
                mobile: detail.storeMobile || '',
                isTakeOut: true,
              },
              imgSrc: pAfterSale,
            });
          }
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
        } else {
          if (detail?.items[0]?.isShowAdjustment == 1) {
            renderInfo.current.btns.push({
              name: '申请退款',
              func: handleApplyAfterSale,
              params: { kind: 1, orderId: detail.id },
            });
          }
        }
        break;
      case -1:
      case 6:
        renderInfo.current.titleName = '运输中';
        renderInfo.current.statusDom = <OrderCompleteInfo orderDetail={detail} />;
        detail.einvoiceId &&
          detail.distributeType == 1 &&
          renderInfo.current.btns.push({
            name: '发票信息',
            func: handleVoinceInfo,
            params: { einvoiceId: detail.einvoiceId },
          });
        detail.distributeType == 1 &&
          renderInfo.current.btns.push({
            name: '确认收货',
            func: handleSureGot,
            params: { orderId: detail.id },
            isPart: true,
          });
        if (detail.distributeType == 2) {
          renderInfo.current.titleName = '待取餐';
          renderInfo.current.statusTipDom = (
            <View className="statusTip">
              <View className="text">等待骑手到店取餐。</View>
            </View>
          );
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
        }
        break;
      case 7:
        renderInfo.current.titleName = '待出餐';
        renderInfo.current.statusTipDom = (
          <View className="statusTip">
            <View className="text">商家正在准备餐。</View>
          </View>
        );
        renderInfo.current.btns.push({
          name: '联系商家',
          func: handleConcat,
          params: { mobile: detail.storeMobile },
          imgSrc: pCallShop,
        });
        break;
      case 8:
        renderInfo.current.titleName = '配送中';
        if (detail.distributeType == 1) {
          renderInfo.current.statusDom = (
            <View className="detailExplain">
              <View className="text">快递配送：配送中，请耐心等待。</View>
            </View>
          );
        } else if (detail.distributeType == 2) {
          if (detail.ddStatus) {
            renderInfo.current.statusTipDom = (
              <View className="statusTip mt12">
                <View className="text">{'配送状态：' + detail.ddStatus}</View>
              </View>
            );
          }
          renderInfo.current.btns.push({
            name: '致电骑手',
            func: handleConcat,
            params: { mobile: detail.dmMobile },
            imgSrc: pCallDriver,
            size4: true,
          });
          renderInfo.current.deliveryCmp = detail.dmName == '商家配送' ? '商家配送' : '达达配送';
          renderInfo.current.deliveryName = detail.dmName == '商家配送' ? '' : detail.dmName;
        } else if (detail.distributeType == 3) {
          renderInfo.current.statusTipDom = (
            <View className="statusTip">
              <View className="text">自取：等待自取中，请及时前往</View>
            </View>
          );
        }
        renderInfo.current.btns.push({
          name: '联系商家',
          func: handleConcat,
          params: { mobile: detail.storeMobile },
          imgSrc: pCallShop,
        });
        break;
      case 9:
        renderInfo.current.titleName = '待自提';
        renderInfo.current.statusTipDom = (
          <View className="statusTip">
            <View className="text">等待自取中，请及时前往</View>
            <View className="mt12">
              <Text className="txt28 black6">预留电话：</Text>
              <Text className="txt28 black3 bold">{detail.mobile}</Text>
            </View>
          </View>
        );
        if (detail?.items[0]?.isShowAdjustment == 1) {
          renderInfo.current.btns.push({
            name: '申请退款',
            func: handleApplyAfterSaleForTakeout,
            params: {
              kind: 1,
              orderId: detail.id,
              mobile: detail.storeMobile || '',
              isTakeOut: true,
            },
            imgSrc: pAfterSale,
          });
        }
        renderInfo.current.btns.push({
          name: '联系商家',
          func: handleConcat,
          params: { mobile: detail.storeMobile },
          imgSrc: pCallShop,
        });
        break;
      case 11:
        renderInfo.current.titleName = '待评价';
        if (detail.type == 1 || detail.type == 4) {
          renderInfo.current.btns.push({
            name: '联系商家',
            func: handleConcat,
            params: { mobile: detail.storeMobile },
            imgSrc: pCallShop,
          });
        }

        renderInfo.current.btns.push({
          name: '立即评价',
          isOutStanding: true,
          func: handleConcat,
          params: { id: detail.id },
          imgSrc: 'pingjia',
          isIcon: true,
          size4: true,
          isPart: true,
        });
        if (detail.distributeType == 2) {
          renderInfo.current.btns.push({
            name: '致电骑手',
            func: handleConcat,
            params: { mobile: detail.dmMobile },
            imgSrc: pCallDriver,
            size4: true,
          });
        }

        // 快递发货
        if (detail.distributeType == 1) {
          renderInfo.current.statusDom = <OrderCompleteInfo orderDetail={detail} />;
        }
        break;
        case 12:
          renderInfo.current.titleName = '已退款';
          break;
      default:
        break;
    }
  };

  return (
    <View className="totalPage_orderDetail">
      <View
        className={[
          'fontPage',
          orderDetail.distributeType == 1 &&
            renderInfo.current.btns.length > 0 &&
            'cutBottom',
        ].join(' ')}
      >
        {/* <DefaultNavBar title="订单详情" /> */}

        <ScrollView
          className="contentPage"
          scrollY
          lowerThreshold={240}
          style={{
            height: '100%',
          }}
        >
          <View className="statusAll">
            <View className="statusName">{renderInfo.current.titleName || ''}</View>

            {(orderDetail.type == 1 || orderDetail.type == 4 || orderDetail.type == 5) && (
              <>
                {orderDetail.distributeType == 1 && renderInfo.current.statusDom}
                {orderDetail.distributeType == 1 && <OrderAddrInfo orderDetail={orderDetail} />}
                {(orderDetail.distributeType == 2 ||
                  orderDetail.distributeType == 3 ||
                  orderDetail.distributeType == 4) && (
                  <OrderStatusInfoTakeOut data={renderInfo.current} />
                )}
                {(orderDetail.distributeType == 2 ||
                  (orderDetail.distributeType == 3 &&
                    orderDetail.status != 1 &&
                    orderDetail.status != 3) ||
                  orderDetail.distributeType == 6) && (
                  <OrderAddrInfoTakeOut orderDetail={orderDetail} />
                )}
              </>
            )}

            {orderDetail.type != 1 &&
              orderDetail.type != 4 &&
              orderDetail.type != 5 &&
              orderDetail.status == 11 && <OrderStatusInfoTakeOut data={renderInfo.current} />}
          </View>

          {(orderDetail.type == 1 || orderDetail.type == 4 || orderDetail.type == 5) &&
            orderDetail.distributeType != 4 && (
              <OrderProductsInfo
                orderDetail={orderDetail}
                handleApplyAfterSale={handleApplyAfterSale}
                handleGoAfterSaleDetail={handleGoAfterSaleDetail}
                saveProductInfo={saveProductInfo}
              />
            )}

          {orderDetail.type && <OrderBaseInfo orderDetail={orderDetail} />}
        </ScrollView>
      </View>

      {renderInfo.current.btns.length > 0 && orderDetail.distributeType == 1 && (
        <View className="bottomArea">
          <View className="operates">
            {renderInfo?.current?.btns?.map((btn, index) => {
              return <View
                className={[
                  'btn',
                  btn.isPart && 'btnPart customePageStyle customePageBorderStyle',
                  btn.isAll && 'btnAll customePageBackgroundStyle',
                ].join(' ')}
                onClick={() => btn.func(btn.params)}
                key={'opBtn_' + index}
              >
                {btn.name}
              </View>
            })}
          </View>
        </View>
      )}

      <OrderCancleReason
        dispatch={dispatch}
        isOpened={isOpened}
        handleClose={cancleReasonClosed}
        handleSelected={handleSelected}
      />

      <StandModal
        isOpened={isOpenedGot}
        cancelText="没收到"
        confirmText="收到了"
        onClose={handleClose}
        onCancel={handleClose}
        onConfirm={handleGot}
        content="您是否收到商品？"
      />
    </View>
  );
};

const getTimeStr = (seconds = 0) => {
  let h = parseInt(seconds / 3600);
  let m = parseInt((seconds - h * 3600) / 60);
  let s = seconds % 60;
  let timeText =
    h > 0 ? h + '小时' + m + '分钟' + s + '秒' : m > 0 ? m + '分钟' + s + '秒' : s + '秒';
  return timeText;
};

const OrderWaitPayInfo = ({ orderDetail, refresh, dispatch }) => {
  const [timeStr, seTimeStr] = useState('');

  let seconds = parseInt(orderDetail.times / 1000);
  let timerId = null;

  useEffect(() => {
    timerId = setInterval(() => {
      if (seconds > 1) {
        seconds -= 1;
      } else {
        seconds = 0;
        clearInterval(timerId);
        dispatch({
          type: 'order/orderCancleModel',
          payload: {
            orderId: orderDetail.id,
            orderCancelReasonStatus: 1,
          },
        }).then(() => {
          refresh(true);
        });
      }
      let timeText = getTimeStr(seconds);
      seTimeStr(timeText);
    }, 1000);
    return () => {
      timerId && clearInterval(timerId);
    };
  }, []);

  return (
    <View className="detailExplain">
      <View className="flex-row--center">
        <View>
          <Text className="text black6">需付款：</Text>
          <Text className="text black3 bold">¥{orderDetail.totalPayment}</Text>
        </View>
        <View className="ml64">
          <Text className="text black6">倒计时：</Text>
          <Text className="text black3 bold">{timeStr}</Text>
        </View>
      </View>
    </View>
  );
};

const OrderWaitSendInfo = () => {
  return (
    <View className="detailExplain">
      <Text className="text">店主打包发货中，请耐心等待！</Text>
    </View>
  );
};

const OrderCompleteInfo = ({ orderDetail }) => {
  const showTransDetai = (account, orderId) => {
    let url = '/orderSubPack/logistics/index?orderId=' + orderId;
    if (account >= 1) {
      url = '/orderSubPack/logisticsList/index';
    }
    Taro.navigateTo({ url });
  };
  const handleCopy = (data) => {
    Taro.setClipboardData({
      data,
      complete: function () {
        Taro.showToast({ title: '复制成功', icon: 'none' });
      },
    });
  };
  let logisticsComName = orderDetail.logisticsComName;
  let logisticsNum = orderDetail.logisticsNum;
  if (orderDetail.logisticsList && orderDetail.logisticsList?.length > 0) {
    logisticsComName = orderDetail.logisticsList[0].logisticsComName;
    logisticsNum = orderDetail.logisticsList[0].logisticsNum;
  }
  return (
    <View className="detailExplain moduleComplete">
      {orderDetail.status == 4 && <View className="text">订单已完成，期待您的再次光临！</View>}
      {(orderDetail.status == 6 || orderDetail.status == -1) && (
        <View className="text">{orderDetail.status == -1 ? '部分发货' : '已发货'}</View>
      )}
      <View
        className="transInfo"
        onClick={() => showTransDetai(orderDetail.logisticsCount, orderDetail.id)}
      >
        <View className="left">
          <Image className="caricon" src={pCar} />
          {orderDetail.logisticsCount > 1 ? (
            <Text className="cpnum chaidan omit-1">
              该订单拆成{orderDetail.logisticsCount}个包裹发出，点击可查看物流详情
            </Text>
          ) : (
            <>
              <Text className="cpname">{logisticsComName}</Text>
              <Text className="cpnum">{logisticsNum}</Text>
              <View
                className="copy"
                onClick={(e) => {
                  e.stopPropagation();
                  handleCopy(logisticsNum);
                }}
              >
                <Image className="ficon" src={pCopy} />
              </View>
            </>
          )}
        </View>
        <View className="right flex-row-center-center">
          <Text className='at-icon at-icon-chevron-right rightIcon'></Text>
        </View>
      </View>
    </View>
  );
};

const OrderCancleInfo = ({ orderDetail }) => {
  return (
    <View className="detailExplain">
      <Text className="text">{'取消原因：' + (orderDetail.cancelReason || '')}</Text>
    </View>
  );
};

const OrderAddrInfo = ({ orderDetail }) => {
  return (
    <View className="theContentOrderDetail noMar moduleAddress">
      <View className="left">
        <Image className="aicon" src={pLocation} />
      </View>
      <View className="right">
        <View className="person flex-row-spaceBetween-center">
          {orderDetail.name && <Text className="text">收件人：{orderDetail.name}</Text>}
          {orderDetail.mobile && <Text className="text">{orderDetail.mobile}</Text>}
        </View>
        <Text className="addr">收件地址：{orderDetail.address}</Text>
      </View>
    </View>
  );
};

const OrderWaitPayInfoTakeOut = ({ orderDetail, refresh, dispatch }) => {
  const [timeStr, seTimeStr] = useState('');

  let seconds = parseInt(orderDetail.times / 1000);
  let timerId = null;

  useEffect(() => {
    timerId = setInterval(() => {
      if (seconds > 1) {
        seconds -= 1;
      } else {
        seconds = 0;
        clearInterval(timerId);
        dispatch({
          type: 'order/orderCancleModel',
          payload: {
            orderId: orderDetail.id,
            orderCancelReasonStatus: 1,
          },
        }).then(() => {
          refresh(true);
        });
      }
      let timeText = getTimeStr(seconds);
      seTimeStr(timeText);
    }, 1000);
    return () => {
      timerId && clearInterval(timerId);
    };
  }, []);

  return (
    <View className="flex-row--center">
      <View>
        <Text className="text black6">需付款：</Text>
        <Text className="text black3 bold">¥{orderDetail.totalPayment}</Text>
      </View>
      <View className="ml64">
        <Text className="text black6">倒计时：</Text>
        <Text className="text black3 bold">{timeStr}</Text>
      </View>
    </View>
  );
};

const OrderStatusInfoTakeOut = ({ data }) => {
  const { btns = [], statusTipDom = null, deliveryCmp = null, deliveryName = '' } = data;
  return (
    <View className="detailExplain moduleStatusTakeOut">
      {deliveryCmp && (
        <View className="flex-row--center">
          <Text className="text black6">配送服务：</Text>
          <Text className="text black3 bold">{deliveryCmp}</Text>
          {deliveryName.length > 0 && (
            <>
              <Text className="text black6 ml68">配送骑手：</Text>
              <Text className="text black3 bold">{deliveryName}</Text>
            </>
          )}
        </View>
      )}
      {statusTipDom}
      <View className="btnsLine">
        {btns.length > 0 &&
          btns.map((btn, index) => (
            <>
              <View
                className="btn"
                onClick={() => btn.func(btn.params)}
                key={'takeOutBtn_' + btn.name + index}
              >
                {btn.isIcon ? (
                  <View className="flex-row-center-center btnIcon">
                    <Icon name={btn.imgSrc} size={42} color={'#ff0d49'} />
                  </View>
                ) : (
                  <Image className="btnIcon" src={btn.imgSrc} />
                )}
                <View className={['btnText', btn.isOutStanding && 'customePageStyle'].join(' ')}>
                  {btn.name}
                </View>
              </View>
            </>
          ))}
      </View>
    </View>
  );
};

const OrderAddrInfoTakeOut = ({ orderDetail }) => {
  //配送方式distributeType 1:快递发货2:同城配送3:到店自提 4:门店买单 5:门店核销 6:无需配送
  return (
    <View className="theContentOrderDetail noMar moduleAddress moduleAddressTakeOut">
      {orderDetail.distributeType == 6 && (
        <View className="flex-row-center-center centerTitle">无需配送</View>
      )}
      {(orderDetail.distributeType == 1 || orderDetail.distributeType == 2) && (
        <>
          <View className="left">
            <Image className="aicon" src={pLocation} />
          </View>
          <View className="right">
            <View className="person flex-row-spaceBetween-center">
              {orderDetail.name && <Text className="text">收件人：{orderDetail.name}</Text>}
              {orderDetail.mobile && <Text className="text">{orderDetail.mobile}</Text>}
            </View>
            <Text className="addr">收件地址：{orderDetail.address}</Text>
          </View>
        </>
      )}
      {orderDetail.distributeType == 3 && orderDetail.status != 1 && orderDetail.status != 3 && (
        <>
          <View className="flex-column-center-center selfTake">
            <Text className="lable">取餐码</Text>
            <Text className="num">{orderDetail.orderNumber}</Text>
          </View>
        </>
      )}
    </View>
  );
};

const OrderProductsInfo = ({
  orderDetail,
  handleApplyAfterSale,
  handleGoAfterSaleDetail,
  saveProductInfo,
}) => {
  let productTotalNum = 0;
  let productListDom = null;
  //跳转到商品详情页
  const goGoods = (goods) => {
    if (orderDetail.type == 1) {
      let url = '/mainSubPack/goodsDetail/index' + '?' + 'id=' + goods.productId;
      Taro.navigateTo({
        url,
      });
    } else if (orderDetail.type == 4) {
      //外卖商品跳转到外卖店铺
      Taro.navigateTo({
        url: `/mainSubPack/takeOutShop/index?orgId=${orderDetail.storeId}&merchantId=${orderDetail.merchantId}`,
      });
    }
  };
  if (orderDetail.items && orderDetail.items.length > 0) {
    productListDom = orderDetail.items.map((item) => {
      let options = JSON.parse(item.optionValue || item.options);
      let sku = '';
      for (let key in options) {
        sku += options[key] + ' ';
      }
      productTotalNum += Number(item.quantity);
      return (
        <>
          <View
            className="product"
            key={'product_' + item.productId}
            onClick={() => {
              goGoods(item);
            }}
          >
            <Image
              className="pic"
              src={item.mediaUrl.indexOf('http') === 0 ? item.mediaUrl : sourceUrl + item.mediaUrl}
            />
            <View className="base">
              <Text className="name textShengnue">{item.title}</Text>
              <Text className="sku textShengnue">{sku}</Text>
              <View className="font-DIN price customePageStyle">
                <Text className="unit">¥</Text>
                <Text>{item.singlePrice}</Text>
              </View>
            </View>
            <View className="num">{'x' + item.quantity}</View>
          </View>
          {(orderDetail.status == 4 || orderDetail.status == 6 || orderDetail.status == 11 || orderDetail.status == 12) &&
            (item.isShowAdjustment == 1 || item.isApplyAdjustment == 1) && (
              <View className="afterSaleOpLine">
                {item.isShowAdjustment == 1 && (
                  <View
                    className="asBtn"
                    onClick={() => {
                      saveProductInfo(item);
                      handleApplyAfterSale({
                        kind: 2,
                        orderId: orderDetail.id,
                        orderItemId: item.orderItemId,
                        detailOrderId: item?.detailOrderId || null,
                      });
                    }}
                  >
                    申请售后
                  </View>
                )}
                {item.isApplyAdjustment == 1 && (
                  <View className="asBtn" onClick={() => handleGoAfterSaleDetail({id:item.orderAdjustmentId})}>
                    售后详情
                  </View>
                )}
              </View>
            )}
        </>
      );
    });
  }
  //跳转到商城页
  const goShop = () => {
    if (orderDetail.type == 1) {
      //商城订单
      Taro.navigateTo({
        url: `/mainSubPack/shoppingMall/index?orgId=${orderDetail.storeId}&merchantId=${orderDetail.merchantId}`,
      });
    } else if (orderDetail.type == 4) {
      //外卖订单
      Taro.navigateTo({
        url: `/mainSubPack/takeOutShop/index?orgId=${orderDetail.storeId}&merchantId=${orderDetail.merchantId}`,
      });
    }
  };
  return (
    <View className="theContentOrderDetail moduleProducts">
      <View className="mendian" onClick={goShop}>
        <Text className="txt">{orderDetail.storeName || ''}</Text>
      </View>
      <View className="productList">{productListDom}</View>
      <View className="divider"></View>
      <View className="total">
        <Text>{'共' + productTotalNum + '件商品'}</Text>
        <Text className="ml20">合计：</Text>
        <Text className="font-DIN bold customePageStyle">{'¥' + orderDetail.totalPrice}</Text>
      </View>
    </View>
  );
};

const OrderBaseInfo = ({ orderDetail }) => {
  const handleCopy = (data) => {
    Taro.setClipboardData({
      data,
      complete: function () {
        Taro.showToast({ title: '复制成功', icon: 'none' });
      },
    });
  };
  return (
    <View className="theContentOrderDetail moduleOrderInfo">
      <View className="lineBetween">
        <Text className="label">订单编号</Text>
        <View className="flex-row--center">
          <Text className="cnt">{orderDetail.id}</Text>
          <View
            className="copy"
            onClick={(e) => {
              e.stopPropagation();
              handleCopy(orderDetail.id);
            }}
          >
            <Image className="ficon" src={pCopy} />
          </View>
        </View>
      </View>
      {orderDetail.created && (
        <View className="lineBetween">
          <Text className="label">下单时间</Text>
          <Text className="cnt">{orderDetail.created}</Text>
        </View>
      )}
      {orderDetail.paymentTime && (
        <View className="lineBetween">
          <Text className="label">支付时间</Text>
          <Text className="cnt">{orderDetail.paymentTime}</Text>
        </View>
      )}
      {orderDetail.type === 5 && (
        <View className="lineBetween">
          <Text className="label" style={{ flexShrink: 0 }}>
            备注&emsp;&emsp;
          </Text>
          <Text className="cnt" style={{ overflow: 'hidden' }}>
            {orderDetail.customerRemark ?? '无'}
          </Text>
        </View>
      )}
      {orderDetail.completedAt && (
        <View className="lineBetween">
          <Text className="label">完成时间</Text>
          <Text className="cnt">{orderDetail.completedAt}</Text>
        </View>
      )}
      <View className="divider"></View>
      <View className="lineBetween">
        <Text className="label">商品金额</Text>
        <View className="cnt">
          <Text className="unit">¥</Text>
          <Text className="num">{orderDetail.totalPrice || 0.0}</Text>
        </View>
      </View>
      {orderDetail.type != 5 && (
        <>
          <View className="lineBetween">
            <Text className="label">运费</Text>
            <View className="cnt">
              <Text className="unit">¥</Text>
              <Text className="num">{orderDetail.freightAmount || 0.0}</Text>
            </View>
          </View>
          <View className="lineBetween">
            <Text className="label">优惠券</Text>
            <View className="cnt">
              <Text className="unit">-¥</Text>
              <Text className="num">{orderDetail.couponAmount || 0.0}</Text>
            </View>
          </View>
        </>
      )}

      {orderDetail.activityDiscountAmount > 0 && (
        <View className="lineBetween">
          <Text className="label">折扣</Text>
          <View className="cnt">
            <Text className="unit">-¥</Text>
            <Text className="num">{orderDetail.activityDiscountAmount}</Text>
          </View>
        </View>
      )}

      <View className="lineBetween">
        <Text className="label">积分</Text>
        <View className="cnt">
          <Text className="unit">-¥</Text>
          <Text className="num">{orderDetail.totalPointAmount || 0.0}</Text>
        </View>
      </View>

      <View className="lineBetween">
        <Text className="label">提货券</Text>
        <View className="cnt">
          <Text className="unit">-¥</Text>
          <Text className="num">{orderDetail.discountAmount || 0.0}</Text>
        </View>
      </View>

      <View className="divider"></View>

      <View className="lineEnd">
        <Text className="endLabel">实际支付金额：</Text>
        <Text className="font-DIN endBold customePageStyle">
          ¥{orderDetail.totalPayment || 0.0}
        </Text>
      </View>
    </View>
  );
};

export default connect(({}) => ({}))(OrderDetail);
